package org.rcloud.io.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.coobird.thumbnailator.Thumbnails;
import org.rcloud.io.Utils.ResultVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import static org.aspectj.weaver.tools.cache.SimpleCacheFactory.path;

/**
 * Created by Administrator on 2019/2/18.
 */

@Controller
public class UploadController {
    private static final Logger LOGGER = LoggerFactory.getLogger(UploadController.class);

    //配置文件的路径
    @Value("${file.staticAccessPath}")
    private String staticAccessPath;
    @Value("${file.uploadFolder}")
    private String uploadFolder;

    @GetMapping("/upload")
    public String upload() {
        return "upload";
    }
    @PostMapping("/upload")
    @ResponseBody
    public ResultVo upload(@RequestParam( value="files",required=false ) MultipartFile file) {
        if (file.isEmpty()) {
            return ResultVo.setError("上传失败，请选择文件");
        }

        long size = file.getSize();
        if (size < 3*1048576) {
            System.out.println("小于3M：" + size);
        } else {
            System.out.println("大于小于3M：" + size);
        }

        //获取文件名
        String fileName = String.valueOf(System.currentTimeMillis())+".jpg";

        File dest = new File(uploadFolder +"images/"+ fileName);

        if(!dest.exists()){
            //先得到文件的上级目录，并创建上级目录，在创建文件
            dest.getParentFile().mkdirs();
            try {
                //创建文件
                dest.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            file.transferTo(dest);

            return ResultVo.setOK("https://wdsx.fywljt.cn/wechat-api-0.0.1-SNAPSHOT/upload/images/"+ fileName);

        } catch (IOException e) {
            LOGGER.error(e.toString(), e);
            return ResultVo.setError("上传失败！");
        }
    }


}
